package com.wxscrmplus.drainage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxscrmplus.common.core.domain.entity.SysUser;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.utils.StreamUtils;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wxscrmplus.customer.domain.FollowUser;
import com.wxscrmplus.customer.mapper.FollowUserMapper;
import com.wxscrmplus.drainage.domain.DraQrcodeUser;
import com.wxscrmplus.drainage.domain.vo.DraChannelVo;
import com.wxscrmplus.drainage.domain.vo.DraQrcodeUserVo;
import com.wxscrmplus.drainage.mapper.DraChannelMapper;
import com.wxscrmplus.drainage.mapper.DraQrcodeUserMapper;
import com.wxscrmplus.statistics.service.IChannelStatsService;
import com.wxscrmplus.system.domain.SysOss;
import com.wxscrmplus.system.domain.vo.SysOssVo;
import com.wxscrmplus.system.mapper.SysUserMapper;
import com.wxscrmplus.system.service.ISysOssService;
import com.wxscrmplus.system.service.ISysUserService;
import com.wxscrmplus.wxcp.factory.WxCpServiceFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
import org.springframework.stereotype.Service;
import com.wxscrmplus.drainage.domain.bo.DraQrcodeBo;
import com.wxscrmplus.drainage.domain.vo.DraQrcodeVo;
import com.wxscrmplus.drainage.domain.DraQrcode;
import com.wxscrmplus.drainage.mapper.DraQrcodeMapper;
import com.wxscrmplus.drainage.service.IDraQrcodeService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 渠道活码Service业务层处理
 *
 * @author 王永超
 * @date 2023-03-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DraQrcodeServiceImpl extends WxCpServiceFactory implements IDraQrcodeService {

    private final DraQrcodeMapper baseMapper;

    private final DraChannelMapper channelMapper;

    private final DraQrcodeUserMapper qrcodeUserMapper;

    private final SysUserMapper userMapper;
    private final ISysUserService userService;

    private final FollowUserMapper followUserMapper;

    private final ISysOssService ossService;

    private final IChannelStatsService channelStatsService;


    /**
     * 查询渠道活码
     */
    @Override
    public DraQrcodeVo queryById(Long qrcodeId) {
        DraQrcodeVo qrcodeVo = baseMapper.selectVoById(qrcodeId);
        DraChannelVo draChannelVo = channelMapper.selectVoById(qrcodeVo.getChannelId());
        if (ObjectUtil.isNotEmpty(draChannelVo)) {
            qrcodeVo.setChannelName(draChannelVo.getName());
        }
        //查询使用成员
        List<DraQrcodeUserVo> qrcodeUserList = qrcodeUserMapper.selectVoList(Wrappers.query(new DraQrcodeUser()).lambda().eq(DraQrcodeUser::getQrcodeId, qrcodeVo.getQrcodeId()));
        List<Long> usingUserIdList = qrcodeUserList.stream().map(DraQrcodeUserVo::getUserId).distinct().collect(Collectors.toList());
        qrcodeVo.setUsingUserIds(usingUserIdList);
        if (CollectionUtil.isNotEmpty(usingUserIdList)) {
            List<SysUser> usingUserList = userMapper.findBatchIds(usingUserIdList);
            qrcodeVo.setUsingUserNickName(String.join("、", StreamUtils.toList(usingUserList, SysUser::getNickName)));
            Map<Long, SysUser> usingUserMap = StreamUtils.toIdentityMap(usingUserList, SysUser::getUserId);
            for (DraQrcodeUserVo draQrcodeUserVo : qrcodeUserList) {
                SysUser sysUser = usingUserMap.get(draQrcodeUserVo.getUserId());
                if (ObjectUtil.isNotEmpty(sysUser)) {
                    draQrcodeUserVo.setNickName(sysUser.getNickName());
                }
            }
            List<Long> onlineUserId = qrcodeVo.getOnlineUserId();
            if (CollectionUtil.isNotEmpty(onlineUserId)) {
                List<SysUser> onlineUserList = userMapper.findBatchIds(onlineUserId);
                qrcodeVo.setOnlineUserNickName(String.join("、", StreamUtils.toList(onlineUserList, SysUser::getNickName)));
            }
            qrcodeVo.setUsingUserList(qrcodeUserList);
        }
        qrcodeVo.setQrcodeUrl(ossService.genOssUrl(qrcodeVo.getQrcode(), 120));
        //查询备用成员
        qrcodeVo.setStandbyUserNickName(userMapper.selectUserByIdContainDel(qrcodeVo.getStandbyUserId()).getNickName());
        return qrcodeVo;
    }

    /**
     * 查询渠道活码列表
     */
    @Override
    public TableDataInfo<DraQrcodeVo> queryPageList(DraQrcodeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DraQrcode> lqw = buildQueryWrapper(bo);
        Page<DraQrcodeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (DraQrcodeVo qrcodeVo : result.getRecords()) {
            DraChannelVo draChannelVo = channelMapper.selectVoById(qrcodeVo.getChannelId());
            if (ObjectUtil.isNotEmpty(draChannelVo)) {
                qrcodeVo.setChannelName(draChannelVo.getName());
            }
            //查询使用成员
            List<DraQrcodeUserVo> qrcodeUserList = qrcodeUserMapper.selectVoList(Wrappers.query(new DraQrcodeUser()).lambda().eq(DraQrcodeUser::getQrcodeId, qrcodeVo.getQrcodeId()));
            List<Long> usingUserIdList = qrcodeUserList.stream().map(DraQrcodeUserVo::getUserId).distinct().collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(usingUserIdList)) {
                List<SysUser> usingUserList = userMapper.findBatchIds(usingUserIdList);
                qrcodeVo.setUsingUserNickName(String.join("、", StreamUtils.toList(usingUserList, SysUser::getNickName)));
                Map<Long, SysUser> usingUserMap = StreamUtils.toIdentityMap(usingUserList, SysUser::getUserId);
                for (DraQrcodeUserVo draQrcodeUserVo : qrcodeUserList) {
                    SysUser sysUser = usingUserMap.get(draQrcodeUserVo.getUserId());
                    if (ObjectUtil.isNotEmpty(sysUser)) {
                        draQrcodeUserVo.setNickName(sysUser.getNickName());
                    }
                }
                qrcodeVo.setUsingUserList(qrcodeUserList);
            }
            List<Long> onlineUserId = qrcodeVo.getOnlineUserId();
            if (CollectionUtil.isNotEmpty(onlineUserId)) {
                List<SysUser> onlineUserList = userMapper.findBatchIds(onlineUserId);
                qrcodeVo.setOnlineUserNickName(String.join("、", StreamUtils.toList(onlineUserList, SysUser::getNickName)));
            }
            qrcodeVo.setQrcodeUrl(ossService.genOssUrl(qrcodeVo.getQrcode(), 120));
            //查询备用成员
            qrcodeVo.setStandbyUserNickName(userMapper.selectUserByIdContainDel(qrcodeVo.getStandbyUserId()).getNickName());

        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询渠道活码列表
     */
    @Override
    public List<DraQrcodeVo> queryList(DraQrcodeBo bo) {
        LambdaQueryWrapper<DraQrcode> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DraQrcode> buildQueryWrapper(DraQrcodeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DraQrcode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getType()), DraQrcode::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getScene()), DraQrcode::getScene, bo.getScene());
        lqw.eq(StringUtils.isNotBlank(bo.getStyle()), DraQrcode::getStyle, bo.getStyle());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), DraQrcode::getRemark, bo.getRemark());
        lqw.eq(StringUtils.isNotBlank(bo.getSkipVerifyType()), DraQrcode::getSkipVerifyType, bo.getSkipVerifyType());
        lqw.between(params.get("beginSkipVerifyStartTime") != null && params.get("endSkipVerifyStartTime") != null,
            DraQrcode::getSkipVerifyStartTime, params.get("beginSkipVerifyStartTime"), params.get("endSkipVerifyStartTime"));
        lqw.between(params.get("beginSkipVerifyEndTime") != null && params.get("endSkipVerifyEndTime") != null,
            DraQrcode::getSkipVerifyEndTime, params.get("beginSkipVerifyEndTime"), params.get("endSkipVerifyEndTime"));
        lqw.eq(bo.getChannelId() != null, DraQrcode::getChannelId, bo.getChannelId());
        lqw.between(params.get("beginDisableTime") != null && params.get("endDisableTime") != null,
            DraQrcode::getDisableTime, params.get("beginDisableTime"), params.get("endDisableTime"));
        lqw.like(StringUtils.isNotBlank(bo.getName()), DraQrcode::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), DraQrcode::getCreateBy, bo.getCreateBy());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            DraQrcode::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), DraQrcode::getUpdateBy, bo.getUpdateBy());
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
            DraQrcode::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.like(StringUtils.isNotBlank(bo.getQwCustomerRemark()), DraQrcode::getQwCustomerRemark, bo.getQwCustomerRemark());
        lqw.like(StringUtils.isNotBlank(bo.getQwCustomerDescription()), DraQrcode::getQwCustomerDescription, bo.getQwCustomerDescription());
        lqw.eq(bo.getWelcomeMsgId() != null, DraQrcode::getWelcomeMsgId, bo.getWelcomeMsgId());
        lqw.eq(bo.getIsSendWelcome() != null, DraQrcode::getIsSendWelcome, bo.getIsSendWelcome());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomStyle()), DraQrcode::getCustomStyle, bo.getCustomStyle());
        lqw.between(params.get("beginOnlineTime") != null && params.get("endOnlineTime") != null,
            DraQrcode::getOnlineTime, params.get("beginOnlineTime"), params.get("endOnlineTime"));
        lqw.between(params.get("beginOfflineTime") != null && params.get("endOfflineTime") != null,
            DraQrcode::getOfflineTime, params.get("beginOfflineTime"), params.get("endOfflineTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getWorkingType()), DraQrcode::getWorkingType, bo.getWorkingType());
        lqw.in(CollectionUtil.isNotEmpty(bo.getWeekday()), DraQrcode::getWeekday, bo.getWeekday());
        lqw.orderByDesc(DraQrcode::getQrcodeId);
        return lqw;
    }

    /**
     * 新增渠道活码
     */
    @Transactional
    @Override
    public Boolean insertByBo(DraQrcodeBo bo) {
        DraQrcode add = BeanUtil.toBean(bo, DraQrcode.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setQrcodeId(add.getQrcodeId());
        }
        //插入使用成员ID关系表
        List<DraQrcodeUser> usingUserList = bo.getUsingUserList();
        for (DraQrcodeUser draQrcodeUser : usingUserList) {
            draQrcodeUser.setQrcodeId(add.getQrcodeId());
        }
        qrcodeUserMapper.insertBatch(usingUserList);

        //创建企微二维码
        WxCpContactWayInfo cpContactWayInfo = new WxCpContactWayInfo();
        WxCpContactWayInfo.ContactWay contactWay = new WxCpContactWayInfo.ContactWay();
        contactWay.setRemark(add.getName());
        contactWay.setType(WxCpContactWayInfo.TYPE.MULTI);
        contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
        contactWay.setState(1 + ":" + add.getQrcodeId());
        //（定时扫描数据库看时间范围是否无需验证）
        boolean skipVerify = add.getSkipVerifyType().equals("quantiankaiqi");
        contactWay.setSkipVerify(skipVerify);
        //获取企业微信userId（系统中的username）
        List<Long> userIdList = usingUserList.stream().map(DraQrcodeUser::getUserId).collect(Collectors.toList());
        List<SysUser> sysUserList = userMapper.selectVoBatchIds(userIdList);
        contactWay.setUsers(sysUserList.stream().map(SysUser::getUserName).collect(Collectors.toList()));
        cpContactWayInfo.setContactWay(contactWay);
        WxCpContactWayResult wxCpContactWayResult = null;
        try {
            for (SysUser sysUser : sysUserList) {
                if (!userService.checkUserNameIsQwUserId(sysUser.getUserName())) {
                    throw new ServiceException(String.format("%s的帐号%s不是企微帐号，无法创建企微二维码", sysUser.getNickName(), sysUser.getUserName()));
                }
            }
            wxCpContactWayResult = getExternalContactService().addContactWay(cpContactWayInfo);
        } catch (WxErrorException e) {
            log.error("生成活码异常：{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        SysOssVo sysOssVo = ossService.upload(wxCpContactWayResult.getQrCode(), SysOss.DownloadFieldEnum.LOGIN.getValue());
        add.setSkipVerify(skipVerify);
        add.setOnlineUserId(userIdList);
        add.setConfigId(wxCpContactWayResult.getConfigId());
        add.setQrcode(sysOssVo.getOssId());
        baseMapper.updateById(add);
        channelStatsService.refreshTotalQrcode(add.getChannelId());
        return flag;
    }

    /**
     * 修改渠道活码
     */
    @Transactional
    @Override
    public Boolean updateByBo(DraQrcodeBo bo) {
        DraQrcode update = BeanUtil.toBean(bo, DraQrcode.class);
        validEntityBeforeSave(update);
        //删除旧的关系数据
        qrcodeUserMapper.delete(Wrappers.query(new DraQrcodeUser()).lambda().eq(DraQrcodeUser::getQrcodeId, bo.getQrcodeId()));
        //插入使用成员ID关系表
        List<DraQrcodeUser> usingUserList = bo.getUsingUserList();
        for (DraQrcodeUser draQrcodeUser : usingUserList) {
            draQrcodeUser.setQrcodeId(bo.getQrcodeId());
        }
        qrcodeUserMapper.insertBatch(usingUserList);

        //企微更新二维码
        WxCpContactWayInfo cpContactWayInfo = new WxCpContactWayInfo();
        WxCpContactWayInfo.ContactWay contactWay = new WxCpContactWayInfo.ContactWay();
        contactWay.setConfigId(update.getConfigId());
        contactWay.setRemark(update.getName());
        contactWay.setType(WxCpContactWayInfo.TYPE.MULTI);
        contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
        //（定时扫描数据库看时间范围是否无需验证）
        boolean skipVerify = update.getSkipVerifyType().equals("quantiankaiqi");
        contactWay.setSkipVerify(skipVerify);
        //获取企业微信userId（系统中的username）
        List<Long> userIdList = usingUserList.stream().map(DraQrcodeUser::getUserId).collect(Collectors.toList());
        List<SysUser> sysUserList = userMapper.selectVoBatchIds(userIdList);
        contactWay.setUsers(sysUserList.stream().map(SysUser::getUserName).collect(Collectors.toList()));
        cpContactWayInfo.setContactWay(contactWay);
        try {
            for (SysUser sysUser : sysUserList) {
                if (!userService.checkUserNameIsQwUserId(sysUser.getUserName())) {
                    throw new ServiceException(String.format("%s的帐号%s不是企微帐号，无法创建企微二维码", sysUser.getNickName(), sysUser.getUserName()));
                }
            }
            WxCpBaseResp wxCpBaseResp = getExternalContactService().updateContactWay(cpContactWayInfo);
            if (!wxCpBaseResp.getErrcode().equals(0L)) {
// 8bd891030e493c33d62f4787f6233702
                throw new ServiceException("生成活码异常");
            }
        } catch (Exception e) {
            log.error("生成活码异常：{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        update.setSkipVerify(skipVerify);
        update.setOnlineUserId(userIdList);
        channelStatsService.refreshTotalQrcode(update.getChannelId());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DraQrcode entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除渠道活码
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<DraQrcodeVo> qrcodeVoList = baseMapper.selectVoBatchIds(ids);
        for (DraQrcodeVo qrcodeVo : qrcodeVoList) {
            try {
                getExternalContactService().deleteContactWay(qrcodeVo.getConfigId());
            } catch (WxErrorException e) {
                log.error("删除企微二维码异常：{}", e.getMessage());
            }
            channelStatsService.refreshTotalQrcode(qrcodeVo.getChannelId());
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void refreshQrcodeUser() {
        QueryWrapper<DraQrcode> queryWrapper = new QueryWrapper<>();
        //开启上限
        queryWrapper.lambda().eq(DraQrcode::getOpenAddLimit, true)
            //时间段无需验证
            .or().eq(DraQrcode::getSkipVerifyType, "xuanzeshijianduan")
            //自动上下线（时间段）
            .or().eq(DraQrcode::getWorkingType, "zidongshangxiaxian");
        List<DraQrcode> qrcodeList = baseMapper.selectList(queryWrapper);
        for (DraQrcode qrcode : qrcodeList) {
            this.refreshQrcodeUser(qrcode);
        }
    }

    @Override
    public void refreshQrcodeUser(DraQrcode qrcode) {
        LocalDateTime now = LocalDateTimeUtil.now();
        boolean skipVerify = true;//无需验证
        if (qrcode.getSkipVerifyType().equals("quantianguanbi")) {
            skipVerify = false;//全天关闭无需验证
        } else if (qrcode.getSkipVerifyType().equals("xuanzeshijianduan")) {
            LocalDateTime skipVerifyStartTime = LocalDateTimeUtil.of(qrcode.getSkipVerifyStartTime());
            skipVerifyStartTime = now.withHour(skipVerifyStartTime.getHour()).withMinute(skipVerifyStartTime.getMinute())
                .withSecond(skipVerifyStartTime.getSecond());
            LocalDateTime skipVerifyEndTime = LocalDateTimeUtil.of(qrcode.getSkipVerifyEndTime());
            skipVerifyEndTime = now.withHour(skipVerifyEndTime.getHour()).withMinute(skipVerifyEndTime.getMinute())
                .withSecond(skipVerifyEndTime.getSecond());
            if (now.isBefore(skipVerifyStartTime) || now.isAfter(skipVerifyEndTime)) {
                //不在时间段范围内，需要验证
                skipVerify = false;
            }
        }
        log.info("skipVerify:{}", skipVerify);
        //使用成员是否在线
        boolean online = true;
        if (qrcode.getWorkingType().equals("zidongshangxiaxian")) {
            int week = LocalDateTimeUtil.dayOfWeek(now.toLocalDate()).getIso8601Value();
            if (!qrcode.getWeekday().contains(String.valueOf(week))) {
                //不在工作日中
                online = false;
            } else {
                LocalDateTime offlineTime = LocalDateTimeUtil.of(qrcode.getOfflineTime());
                offlineTime = now.withHour(offlineTime.getHour()).withMinute(offlineTime.getMinute())
                    .withSecond(offlineTime.getSecond());
                LocalDateTime onlineTime = LocalDateTimeUtil.of(qrcode.getOnlineTime());
                onlineTime = now.withHour(onlineTime.getHour()).withMinute(onlineTime.getMinute())
                    .withSecond(onlineTime.getSecond());
                if (now.isBefore(onlineTime) || now.isAfter(offlineTime)) {
                    //不在工作时间段范围内
                    online = false;
                }
            }
        }
        log.info("online:{}", online);
        //在线客户ID列表
        List<Long> onlineUserIdList = new ArrayList<>();
        if (online) {
            //使用成员列表
            List<DraQrcodeUserVo> qrcodeUserList = qrcodeUserMapper.selectVoList(Wrappers.query(new DraQrcodeUser()).lambda().eq(DraQrcodeUser::getQrcodeId, qrcode.getQrcodeId()));
            for (DraQrcodeUserVo draQrcodeUserVo : qrcodeUserList) {
                //开启上限，需要判断使用成员上限（超出上限踢出二维码）
                if (qrcode.getOpenAddLimit()) {
                    //当天添加的客户数量
                    Long addQty = followUserMapper.selectCount(Wrappers.query(new FollowUser())
                        .lambda().eq(FollowUser::getQrcodeTableType, 1)
                        .eq(FollowUser::getQrcodeId, qrcode.getQrcodeId())
                        .eq(FollowUser::getUserId, draQrcodeUserVo.getUserId())
                        .between(FollowUser::getQwCreatetime, LocalDateTimeUtil.now().withHour(0).withMinute(0).withSecond(0),
                            LocalDateTimeUtil.now().plusDays(1)));
                    if (addQty < draQrcodeUserVo.getAddLimitQty()) {
                        //当天添加数量小于上限数量
                        onlineUserIdList.add(draQrcodeUserVo.getUserId());
                    }
                } else {
                    onlineUserIdList.add(draQrcodeUserVo.getUserId());
                }
            }
        }
        log.info("qrcode：{}\n，onlineUserIdList:{}", qrcode, onlineUserIdList);
        if (CollUtil.isEmpty(onlineUserIdList)) {
            //无人在线使用备用成员
            onlineUserIdList.add(qrcode.getStandbyUserId());
        }

        DraQrcode updateQrcode = new DraQrcode();
        updateQrcode.setQrcodeId(qrcode.getQrcodeId());
        updateQrcode.setSkipVerify(skipVerify);
        updateQrcode.setOnlineUserId(onlineUserIdList);
        updateQrcode.setUpdateBy(qrcode.getUpdateBy());

        //企微更新二维码
        WxCpContactWayInfo cpContactWayInfo = new WxCpContactWayInfo();
        WxCpContactWayInfo.ContactWay contactWay = new WxCpContactWayInfo.ContactWay();
        contactWay.setConfigId(qrcode.getConfigId());
        contactWay.setRemark(qrcode.getName());
        contactWay.setType(WxCpContactWayInfo.TYPE.MULTI);
        contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
        contactWay.setSkipVerify(skipVerify);
        //获取企业微信userId（系统中的username）
        List<SysUser> sysUserList = userMapper.selectVoBatchIds(onlineUserIdList);
        contactWay.setUsers(sysUserList.stream().map(SysUser::getUserName).collect(Collectors.toList()));
        cpContactWayInfo.setContactWay(contactWay);
        try {
            WxCpBaseResp wxCpBaseResp = getExternalContactService().updateContactWay(cpContactWayInfo);
            log.info("wxCpBaseResp:{}", wxCpBaseResp.toJson());
            if (!wxCpBaseResp.getErrcode().equals(0L)) {
                throw new ServiceException("更新活码异常");
            }
        } catch (Exception e) {
            log.error("更新活码异常：{}", e.getMessage());
            throw new ServiceException("更新活码异常");
        }
        baseMapper.updateById(updateQrcode);
    }

}
